package com.jetinno.jetinnosystemclient;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.SystemClock;
import android.support.annotation.UiThread;
import android.support.annotation.WorkerThread;
import android.support.v4.content.FileProvider;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by zhangyuncai.
 * Date: 2022/3/26
 */
public class ClientTimer {

    private static final String TAG = "ClientTimer";
    private static final String JetinnoSystemApkPath = Environment.getExternalStorageDirectory() + File.separator + "Jetinno" + File.separator + "jetinnosystem.apk";
    private final static int minJetinnoSystemVersionCode = 16;//看门狗APP要求的最低版本

    private static ClientTimer _instance = null;

    private Context context;

    private int installedJetinnoSystemVersionCode = 0;//已经安装的看门狗APP的版本
    private int jetinnoSystemHbInterval = 0;//收到看门狗APP心跳的时间间隔
    private volatile boolean isCopyApking = false;//正在复制文件
    private long aLong = 0;//宿主APP已运行时长
    private boolean isOpenDog = true;//是否开启看门狗

    public static ClientTimer getInstance() {
        if (_instance == null) {
            synchronized (ClientTimer.class) {
                if (_instance == null) {
                    _instance = new ClientTimer();
                }
            }
        }
        return _instance;
    }

    private ClientTimer() {
        logToFile("ClientTimer.new");
    }

    public void init(Context applicationContext,boolean isOpenDog) {
        logToFile("ClientTimer.init");
        this.isOpenDog=isOpenDog;
        this.context = applicationContext;
        getClientAppVersionCode();
    }

    ///自主设置是否启用看门狗
    public void setOpenDog(boolean openDog) {
        isOpenDog = openDog;
    }

    private void getClientAppVersionCode() {
        PackageManager packageManager = context.getPackageManager();
        try {
            PackageInfo packageInfo = packageManager.getPackageInfo(ClientConstant.JETINNO_SYSTEM_PACKAGE_NAME, 0);
            if (installedJetinnoSystemVersionCode <= 0) {
                installedJetinnoSystemVersionCode = packageInfo.versionCode;
            }
            printLog("installedJetinnoSystemVersionCode:" + installedJetinnoSystemVersionCode);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 接收宿主APP的心跳
     *
     * @param aLong 宿主APP已运行时长
     */
    public void receiveAppTimer(long aLong) {
        this.aLong = aLong;

        if (context == null) {
            return;
        }

        if (!isOpenDog()) {
            return;
        }

        if (aLong == 20 || aLong == 240 || aLong == 480 || aLong == 960) {//定时检测看门狗APP的版本
            checkJetinnoSystemVersionCode();
        }

        jetinnoSystemHbInterval++;
        if (aLong % 30 == 0) {//定时打印日志
            printLog("dogHbInterval:" + jetinnoSystemHbInterval);
        }
        if (jetinnoSystemHbInterval > 30) {//超过一定时间没有收到看门狗心跳信息,启动看门狗的APP
            logToFile("超过一定时间没有收到看门狗心跳信息");
            jetinnoSystemHbInterval = 0;

            if (isCopyApking) {//正在复制文件并安装APP
                logToFile("正在复制文件并安装APP");
                return;
            }

            ClientProcessUtils.getInstance().exitApp(ClientConstant.JETINNO_SYSTEM_PACKAGE_NAME);
            SystemClock.sleep(1000);

            if (isInstalledDogApp()) {//如果安装了看门狗的APP,则启动App
                logToFile("如果安装了看门狗的APP,则启动App");
                Intent intent = context.getPackageManager().getLaunchIntentForPackage(ClientConstant.JETINNO_SYSTEM_PACKAGE_NAME);
                intent.putExtra(ClientConstant.LAUNCH_SOURCE, context.getPackageName());
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
                return;

            }

            copyApkFile();
            return;

        }

    }

    /**
     * 接收看门狗APP的心跳
     *
     * @param installedJetinnoSystemVersionCode
     */
    public void receiveDogTimer(int installedJetinnoSystemVersionCode) {
        if (context == null) {
            return;
        }
        this.installedJetinnoSystemVersionCode = installedJetinnoSystemVersionCode;
        jetinnoSystemHbInterval = 0;
        if (aLong % 30 == 0) {//定时打印日志
            printLog("installedJetinnoSystemVersionCode:" + installedJetinnoSystemVersionCode);
        }
    }

    private void checkJetinnoSystemVersionCode() {
        if (installedJetinnoSystemVersionCode < minJetinnoSystemVersionCode) {
            logToFile(String.format("update jetinnosystem app,%d,%d", installedJetinnoSystemVersionCode, minJetinnoSystemVersionCode));
            copyApkFile();
        }
    }

    private boolean isInstalledDogApp() {
        return context.getPackageManager().getLaunchIntentForPackage(ClientConstant.JETINNO_SYSTEM_PACKAGE_NAME) != null;
    }

    /**
     * 子线程工作
     */
    @WorkerThread
    private void copyApkFile() {
        logToFile("copyApkFile:" + isCopyApking);
        if (isCopyApking) {
            return;
        }
        isCopyApking = true;

        new Thread() {
            @Override
            public void run() {


                InputStream inputStream = null;
                FileOutputStream fileOutputStream = null;
                try {
//                    inputStream = context.getAssets().open("jetinnosystem");
                    inputStream = context.getResources().openRawResource(R.raw.jetinnosystem);
                    if (inputStream == null) {
                        printLog("inputStream==null");
                        return;
                    }
                    File apkFile = new File(JetinnoSystemApkPath);
                    if (apkFile.exists()) {
                        boolean delete = apkFile.delete();
                        logToFile("delete:" + delete);
                    }
                    apkFile.createNewFile();
                    fileOutputStream = new FileOutputStream(apkFile);
                    byte[] temp = new byte[1024];
                    int length = 0;
                    while ((length = inputStream.read(temp)) > 0) {
                        fileOutputStream.write(temp, 0, length);
                    }
                    fileOutputStream.flush();
                    SystemClock.sleep(3000);
                    if (apkFile.exists()) {
                        installApk();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (inputStream != null) {
                        try {
                            inputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fileOutputStream != null) {
                        try {
                            fileOutputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                isCopyApking = false;
            }
        }.start();
    }

    /**
     * 安装APK
     */
    @UiThread
    private void installApk() {
        logToFile("installApk");
        File apkFile = new File(JetinnoSystemApkPath);
        if (!apkFile.exists()) {
            return;
        }
        logToFile("install apk=>" + JetinnoSystemApkPath);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//适配7.0以上
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileProvider", apkFile);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile),
                    "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }

    /**
     * 是否打开看门狗功能
     * 默认关闭
     *
     * @return
     */
    public boolean isOpenDog() {
        return isOpenDog;
    }

    private void printLog(String msg) {
        Log.i(TAG, msg);
    }

    private void logToFile(String msg) {
        if (context == null) {
            return;
        }
        Intent intent = new Intent(ClientConstant.JETINNO_COFFEE_LOG_ACTION);
        intent.putExtra(ClientConstant.JETINNO_COFFEE_LOG_MESSAGE, msg);
        intent.putExtra(ClientConstant.JETINNO_COFFEE_LOG_CLASSNAME, TAG);
        intent.putExtra(ClientConstant.JETINNO_COFFEE_LOG_LOGTYPE, "operation");
        context.sendBroadcast(intent);
    }
}
